📜 [專欄新文章] Solidity Weekly #6
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
constructor 的新寫法
還在用 function contract_name 當 solidity 智能合約 constructor 嗎? 雖然目前還可以用, 但 deprecated 的寫法, 以後 compilers 可能就不支援了.
跟手機 OS 升級一樣, 每次 Solidity 新版本出來, 就是為了修要一些 bugs, 也同時讓寫出來的 code 更安全. 所以請儘早把 舊的寫法改掉, 且用最新的編譯器來編譯.
例如:
contract Ownable { address public owner;
function Ownable() public { owner = msg.sender; }}
改成
contract Ownable { address public owner;
constructor() public { // <--- 這一行 改用 constructor owner = msg.sender; }}
不建議再用 function 加上 contract name 來當 constructor 是因為, 避免 contract name 被 rename, 卻忘了改 constructor 的 function name 產生的問題, 所以有此寫法上有了此的新設計.
Solidity v0.4.23 之前, 還有可能同時寫兩個 constructor, 一個新的寫法, 一個舊的寫法. 但只執行其中一個. 在 ^0.4.23 修正了這個問題.
*適用版本 Solidity 0.4.22 或以上
Solidity Weekly #6 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌